﻿// Copyright: 2012
// Author: Minh Vu - YoungJ
// File: FeedData.cs - PhoneAppRssReader - PhoneAppRssReader
// Time: 1:19 AM 04/18/2012

using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Xml;
using System.Xml.Linq;
using PhoneAppRssReader.Utls;

namespace PhoneAppRssReader.Entity
{

    public class FeedData : MyBase
    {
        private string title;
        public string Title
        {
            get { return title; }
            set
            {
                if (value == null) return;
                title = value;
                OnPropertyChanged("Title");
            }
        }

        private string description;
        public string Description
        {
            get { return description; }
            set
            {
                if (value == null) return;
                description = value;
                OnPropertyChanged("Description");
            }
        }

        private DateTime pubDate;
        public DateTime PubDate
        {
            get { return pubDate; }
            set
            {
                pubDate = value;
                OnPropertyChanged("PubDate");
            }
        }


        private ObservableCollection<FeedItem> _feedItems = new ObservableCollection<FeedItem>();
        public ObservableCollection<FeedItem> FeedItems
        {
            get { return _feedItems; }
            set
            {
                if (value == null || value.Equals(_feedItems)) return;
                _feedItems = value;
                OnPropertyChanged("FeedItems");
            }
        }

        public bool IsDataLoaded { get; set; }

        public void GetFeedItems(Feed f)
        {
            //if update time of feed < Datetime.Now -30, not download rss xml, using local rss xml 
            if (DateTime.Now.CompareTo(f.Update.AddMinutes(App.UpdateTime)) < 0)
            {
                if (GetFeedLocal(f))
                    return;
            }


            GetFeedWebClient(f);
        }

        public void GetFeedWebClient(Feed f)
        {
            //get (download) rss feed in request on web
            var client = new WebClient();
            client.DownloadStringCompleted += (sender, e) =>
                                                  {
                                                      var newDate = new DateTime();
                                                      var oldDate =
                                                          XmlAction.GetPublishDateRssSource(
                                                              XmlAction.ReadRssSource(f.Id + ".xml"));

                                                      if (e.Error == null)
                                                      {
                                                          newDate = XmlAction.GetPublishDateRssSource(e.Result);
                                                          XmlAction.SaveRssFeedWeb(f.Id, e.Result);
                                                      }

                                                      if (!GetFeedLocal(f))
                                                      {
                                                          Error = "Get feed failure";
                                                          return;
                                                      }

                                                      if (newDate.CompareTo(oldDate) < 0) return;

                                                      foreach (
                                                          var item in
                                                              FeedItems.Where(
                                                                  item => oldDate.CompareTo(item.PubDate) < 0))
                                                      {
                                                          item.IsNew = true;
                                                      }
                                                  };

            client.DownloadStringAsync(new Uri(f.Url, UriKind.Absolute));
        }

        private bool GetFeedLocal(Feed f)
        {
            IsDataLoaded = true;

            var xml = XmlAction.ReadRssSource(f.Id + ".xml");

            if (string.IsNullOrEmpty(xml)) return false;

            try
            {
                var strReader = new StringReader(xml);
                var xmlReader = XmlReader.Create(strReader);
                var feed = SyndicationFeed.Load(xmlReader);
                Title = feed.Title.Text;
                Description = feed.Description == null ? string.Empty : feed.Description.Text;
                FeedItems = XmlParser.FeedItemsParser(feed.Items);
                return true;
            }
            catch (Exception ex)
            {
                try
                {
                    var root = XElement.Parse(xml);
                    Title = root.Descendants("title").First().Value;
                    Description = root.Descendants("description").First().Value;
                    FeedItems = XmlParser.FeedItemsParser(xml);

                    return true;
                }
                catch (Exception)
                {
                    Error = ex.Message;
                }
            }
            return false;
        }

    }
}